<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace extend\weixin\mini;

use extend\weixin\BaseMiniRequest;
use extend\weixin\WxConf;
use extend\weixin\WxMini;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

/**
 * 小程序登录
 * ```php
 * $request = new Jscode2session([
 *      'js_code' => '0e3kQvGa1s1npG0PApHa1QLfKu0kQvGi',
 * ]);
 * $wxClient = \extend\Extend::wxmini()->setRequest($request);
 * $state = $wxClient->execute();
 * if ($state) {
 *      var_export($wxClient->result);
 * } else {
 *      echo $wxClient->error;
 * }
 * ```
 *
 * @auther clevstn
 * @since 2.0
 * @datetime 2023.11.22 14:58
 */
class Jscode2session extends BaseMiniRequest
{
    /**
     * {@inheritdoc}
     */
    public $isLogged = false;
    /**
     * @var array The request options.
     */
    private $_requestOptions;

    /**
     * @param array $requestOptions The request options.
     * ```php
     * $requestOptions = [
     *     'js_code' => 'wx3544654568748dfsds',
     * ];
     *
     * ```
     */
    public function __construct(array $requestOptions)
    {
        $this->_requestOptions = ArrayHelper::merge([
            'appid' => WxConf::APPID,
            'secret' => WxConf::APP_SECRET,
            'grant_type' => 'authorization_code',
        ], $requestOptions);
    }

    /**
     * {@inheritdoc}
     */
    public function getRequestOptions()
    {
        return [
            'query' => $this->_requestOptions,
            'verify' => false,
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getChain()
    {
        return '/sns/jscode2session';
    }

    /**
     * {@inheritdoc}
     */
    public function getMethodAsync()
    {
        return 'getAsync';
    }

    /**
     * {@inheritdoc}
     */
    public function getServiceName()
    {
        return '小程序登录';
    }

    /**
     * {@inheritdoc}
     */
    public function responseCallback($response, WxMini $wxMini)
    {
        return static function () use ($response, $wxMini) {
            $body = Json::decode($response->getBody());
            if (!empty($body['errcode'])) {
                $wxMini->error = $body['errmsg'];
                return false;
            } else {
                $wxMini->result = $body;
                return true;
            }
        };
    }
}